import tastypie
from tastypie import fields
from tastypie.api import Api
from tastypie.exceptions import *
from weblib.django.tastypie._all import *
from .models import *


class DatasetAuthorization(UserReadOnlyAuthorization):
    def read_list(self, object_list, bundle):
        public_datasets = object_list.filter(public=True)
        final_datasets = public_datasets
        user = bundle.request.user
        if hasattr(user, 'data_setting'):
            user_datasets = user.data_setting.accessible_datasets.all()
            final_datasets = final_datasets | user_datasets

        if user.is_company_user and hasattr(user.company, 'data_setting'):
            company_datasets = user.company.data_setting.accessible_datasets.all()
            final_datasets = final_datasets | company_datasets

        res = final_datasets.distinct()
        return res

    def read_detail(self, object_list, bundle):
        dataset = bundle.obj
        user = bundle.request.user
        if dataset.public:
            return True

        if hasattr(user, 'data_setting') and dataset in user.data_setting.accessible_datasets.all():
            return True

        if user.is_company_user:
            company = user.company
            if hasattr(company, 'data_setting') and dataset in company.data_setting.accessible_datasets.all():
                return True

        return False


class DatasetMoldResource(ModelResource):
    info_template = fields.CharField(attribute="info_template")

    class Meta:
        always_return_data = True
        queryset = DatasetMold.objects.all()
        resource_name = 'mold'
        fields = ['name', 'desc', 'note', 'update_dt']

      #  authentication = DjangoOrBasicAuthentication()
        # authorization = Authorization()
        detail_uri_name = 'name'


class DatasetResource(ModelResource):
    info = fields.DictField(attribute='info', use_in='detail')
    mold_name = fields.CharField(attribute='mold_name')
    schema = fields.DictField(attribute=None, use_in='detail')

    class Meta:
        always_return_data = True
        queryset = DataSet.objects.all().order_by('priority')
        resource_name = 'dataset'
        fields = ['name', 'desc', 'size', 'update_dt', 'priority']
      #  authentication = DjangoOrBasicAuthentication()
      #  authorization = DatasetAuthorization()

        detail_uri_name = 'name'

    def dehydrate_schema(self, bundle):
        return bundle.obj.dataset.get_schema(request=bundle.request)


REGLIST = [DatasetMoldResource, DatasetResource]
datakeeper_api = Api(api_name='api')
for to_reg in REGLIST:
    datakeeper_api.register(to_reg())
